package com.cskaoyan.mall.controller.admin;

import com.cskaoyan.mall.bean.bo.AdminLoginBo;
import com.cskaoyan.mall.bean.vo.ResultVO;
import com.cskaoyan.mall.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.security.SecureRandom;
import java.util.HashMap;

@RestController
@RequestMapping("/admin/auth")
public class AuthController {
    @Autowired
    AdminService adminService;
    @RequestMapping("login")
    public ResultVO login(@RequestBody AdminLoginBo loginBo){
//        if(adminService.checkUserLoginInfo(loginBo)){
//            return ResultVO.ok(session.getId());
//        }
//        return ResultVO.error(605, "用户帐号或密码不正确");
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(loginBo.getUsername(), loginBo.getPassword()));
        }catch (AuthenticationException e){
            return ResultVO.error(605, "用户帐号或密码不正确");
        }
        return ResultVO.ok(subject.getSession().getId());
    }

    @GetMapping(value = "info", params = "token != null")
    public ResultVO getInfo(String token){
        // todo: shiro整合后才能实现
        HashMap<String, Object> map = new HashMap<>();
        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        map.put("name", "admin123");
        map.put("perms", new String[]{"*"});
        map.put("roles", new String[]{"系统管理员", "超级管理员", "推广管理员", "商城管理员", "自定义角色A"});
        return ResultVO.ok(map);
    }

    @RequestMapping("index")
    public ResultVO index(){
        return ResultVO.error(501, "请登录");
    }

    @RequestMapping("unAuth")
    public ResultVO unauthorized(){
        return ResultVO.error(506, "没有操作权限，请联系管理员授权");
    }

    @RequestMapping("logout")
    public ResultVO logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultVO.ok();
    }
}
